I was recently confused by this simple question.
/*
Declare a function 'add'.
'add' takes one number input: 'x'.
'add' returns a function that takes one number input 'y'.
This returned function returns the sum of 'x' and 'y' when run.
*/
Did you try to solve it? Here is one possible answer
function add(x) {
return function innerFunction(y) {
return x + y
}
}
//example
const addTwo = add(2) //stores the inner function with x inherited
const sum = addTwo(3) // inputs y as 3
//sum = 5
That, my friend, is a higher-order function.
Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.
The code above is an example of returning a function that inherits the outer scope’s function variable
Here is an example of using a function as an input
const greetPerson = (name, greetingBuilder) =>
console.log(greetingBuilder(name))
const howsItGoing = name => `${name}! How's it going?`
const hello = name => `Hello ${name}`
greetPerson("Jon", howsItGoing) // Jon! Hows'it going?
greetPerson("Fred", hello) // Hello Fred
Not too scary, after all.
You might have noticed that there are a few Array Methods that take functions as inputs… well… that… makes them HIGHER ORDER FUNCTIONS!!
My favorite array method
Array.prototype.map()
const array1 = [1, 4, 9, 16]
// pass a function to map
const map1 = array1.map(x => x * 2)
console.log(map1)
// expected output: Array [2, 8, 18, 32]
Cool right?
Here are some free resources
Did you enjoy this article? Or did I get something wrong?
Feel free to contact me using my website
Have a fantastic day!